<!--
 * @Description: 巡视记录新增或编辑
 * @Author: Liu Zhiwang
 * @Date: 2021-04-13 17:05:40
 * @LastEditTime: 2021-07-29 18:37:10
 * @LastEditors: Liu Zhiwang
-->
<template>
  <div>
    <base-dialog
      class="dialog_box dialog-body-fieldset jcw-repair-edit"
      width="60%"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @updateData="updateData"
      @open="beforeOpenDialog">
      <el-form
        ref="dataForm"
        :model="dialog.form"
        :rules="rules"
        :disabled="dialog.disabled"
        label-width="120px">
        <fieldset>
          <legend>天窗计划</legend>
          <el-row>
            <el-col :span="8">
              <el-form-item label="巡视日期" prop="inspectDate">
                <el-date-picker
                  v-model="dialog.form.inspectDate"
                  format="yyyy-MM-dd"
                  type="date"
                  style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="线路" prop="lineId">
                <el-select
                  v-model="dialog.form.lineId"
                  :no-data-text="dialog.form.deptId ? '' : '请先选择工区'"
                  value-key="lineId"
                  placeholder="线路"
                  clearable
                  :popper-append-to-body="false"
                  class="filter-item">
                  <el-option v-for="(value,i) in dataList.lineData" :key="'dutyDeptAttr'+i" :label="value.lineName" :value="value.lineId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" prop="deptId">
                <select-tree
                  v-model="dialog.form.deptId"
                  node-click
                  :options="dataList.deptData"
                  :props="{ label: 'label', value: 'id', parent: 'parentId', children: 'children' }"
                  @nodeClick="changeLine"
                  @clear="dialog.form.deptId=''" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" style="margin-top: -1px">
              <div class="time-box">
                <el-form-item label="作业时间" prop="workDateTimeRange">
                  <el-date-picker
                    v-model="dialog.form.workDateTimeRange"
                    format="HH:mm"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="申请时间"
                    type="datetimerange"
                    popper-class="daily-car-time-class"
                    @change="getMinutes(dialog.form.workDateTimeRange, 'workSpendMinutes')" />
                </el-form-item>
                <div class="minutes-item"> {{ dialog.form.workSpendMinutes }} 分钟</div>
              </div>
            </el-col>
            <el-col :span="8">
              <el-form-item label="巡视类型" prop="dictInspectTypeId">
                <el-select v-model="dialog.form.dictInspectTypeId" value-key="itemValue" clearable>
                  <el-option v-for="(list,i) in dataList.inspectTypeData" :key="'inspectType'+i" :label="list.itemName" :value="list.dictionaryId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业领导人" prop="workLeader">
                <select-table
                  v-if="dialog.visible"
                  ref="workLeader"
                  v-model="dialog.form.workLeader"
                  :filter-form="selectTableModelWorkLeader.filterForm"
                  :filter-data="selectTableModelWorkLeader.filterData"
                  :default-data="dataList.workLeaderData"
                  :columns="selectTableModelWorkLeader.columns"
                  :total="selectTableModelWorkLeader.total"
                  :filter-fn="selectTableModelWorkLeader.filterFn"
                  @current-change="changeTableItemWorkLeader"
                  @clear="dialog.form.workLeader='';dialog.form.workLeaderId=''" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="跟班领导" prop="followLeader">
                <select-table
                  v-if="dialog.visible"
                  ref="followLeader"
                  v-model="dialog.form.followLeader"
                  :filter-form="selectTableModelFollowLeader.filterForm"
                  :filter-data="selectTableModelFollowLeader.filterData"
                  :default-data="dataList.followLeaderData"
                  :columns="selectTableModelFollowLeader.columns"
                  :total="selectTableModelFollowLeader.total"
                  :filter-fn="selectTableModelFollowLeader.filterFn"
                  @current-change="changeTableItemFollowLeader"
                  @clear="dialog.form.followLeader='';dialog.form.followLeaderId=''" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="跟班领导电话" prop="followLeaderPhone">
                <el-input v-model="dialog.form.followLeaderPhone" type="text" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="巡视人员" prop="inspectPeopleList">
                <select-table-multiple
                  v-if="dialog.visible"
                  ref="inspectPeopleList"
                  value-key="staffId"
                  label-key="staffName"
                  table-value-key="staffId"
                  :data="dialog.form.inspectPeopleList"
                  :filter-form="selectTableModelInspectPeople.filterForm"
                  :filter-data="selectTableModelInspectPeople.filterData"
                  :default-data="dataList.inspectPeopleData"
                  :columns="selectTableModelInspectPeople.columns"
                  :collapse-tags="false"
                  :total="selectTableModelInspectPeople.total"
                  :filter-fn="selectTableModelInspectPeople.filterFn"
                  @selection-change="changeTableItemInspectPeople"
                  @clear="dialog.form.inspectPeopleList=[]" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="跟班干部" prop="followCadre">
                <select-table
                  v-if="dialog.visible"
                  ref="followCadre"
                  v-model="dialog.form.followCadre"
                  :filter-form="selectTableModelFollowCadre.filterForm"
                  :filter-data="selectTableModelFollowCadre.filterData"
                  :default-data="dataList.followCadreData"
                  :columns="selectTableModelFollowCadre.columns"
                  :total="selectTableModelFollowCadre.total"
                  :filter-fn="selectTableModelFollowCadre.filterFn"
                  @current-change="changeTableItemFollowCadre"
                  @clear="dialog.form.followCadre='';dialog.form.followCadreId=''" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="跟班干部电话" prop="followCadrePhone">
                <el-input v-model="dialog.form.followCadrePhone" type="text" maxlength="20" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="巡视区段" prop="inspectRange">
                <el-input v-model="dialog.form.inspectRange" maxlength="500" type="textarea" resize="none" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="巡视内容" prop="inspectContent">
                <el-input v-model="dialog.form.inspectContent" maxlength="500" type="textarea" resize="none" />
              </el-form-item>
            </el-col>
          </el-row>
        </fieldset>
        <fieldset>
          <legend>作业完成情况</legend>
          <el-row>
            <el-col :span="8">
              <el-form-item label="巡视方式" prop="dictInspectWayId">
                <el-select v-model="dialog.form.dictInspectWayId" value-key="itemValue" clearable>
                  <el-option v-for="(list,i) in dataList.inspectWayData" :key="'inspectWay'+i" :label="list.itemName" :value="list.dictionaryId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总人数" prop="inspectPersonCount">
                <el-input v-model="dialog.form.inspectPersonCount" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否异常" prop="isNormal">
                <el-radio-group v-model="dialog.form.isNormal">
                  <el-radio label="NO">否</el-radio>
                  <el-radio label="YES">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="司机" prop="driver">
                <el-input v-model="dialog.form.driver" maxlength="20" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车号/车次" prop="inspectTrainNum">
                <el-input v-model="dialog.form.inspectTrainNum" maxlength="20" type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="存在问题" prop="problemContent">
                <el-input v-model="dialog.form.problemContent" maxlength="500" type="textarea" resize="none" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="处理情况" prop="treatment">
                <el-input v-model="dialog.form.treatment" maxlength="500" type="textarea" resize="none" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="memo">
                <el-input v-model="dialog.form.memo" maxlength="500" type="textarea" resize="none" />
              </el-form-item>
            </el-col>
          </el-row>
        </fieldset>
        <fieldset>
          <legend>附件</legend>
          <el-form-item label="附件上传">
            <UploadFile :model="fileModal" @on-success="uploadSuccess" />
          </el-form-item>
        </fieldset>
      </el-form>
    </base-dialog>
  </div>
</template>
<script>
import { getStaffList } from '@/api/main'
import { valiInt } from '@/utils/validate'
import UploadFile from '@/views/cms/jcwsc/components/UploadFile'
import { addEditMulInspectData } from '@/api/jcwsc/production-daily/catenary-safety-production'
import { getLineList, getDeptAndSubDeptList, getListFindByDtId, findManageDeptTree } from '@/api/main'

export default {
  components: {
    UploadFile
  },
  props: {
    dialog: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      fileModal: {
        title: '',
        visible: false,
        pathList: [],
        fileList: [],
        type: 1,
        bizType: '1',
        key: 0,
        index: 0,
        isDetail: false,
        uploadType: 'file'
      },
      selectTableModelFollowLeader: { // 跟班领导
        filterForm: {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
          // 暂时注释
          // dtId: 'POSITION_TYPE',
          // dtItemValue: '0001'
        },
        filterData: {
          staffName: {
            key: 'staffName',
            type: 'input',
            placeholder: '姓名'
          },
          deptId: {
            clearable: false,
            key: 'deptId',
            type: 'selectTree',
            title: '部门',
            placeholder: '请选择部门',
            options: [],
            props: {
              label: 'label',
              value: 'id',
              parent: 'parentId',
              children: 'children'
            },
            changeFn: _ => {
              this.$refs.followLeader.$refs.customSelect.focus()
            }
          }
        },
        columns: [
          { property: 'staffName', label: '跟班领导' },
          { property: 'deptName', label: '所属部门' },
          { property: 'phone', label: '联系方式' }
        ],
        total: 0,
        filterFn: getStaffList
      },
      selectTableModelFollowCadre: { // 跟班干部
        filterForm: {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
          // 暂时注释
          // dtId: 'POSITION_TYPE',
          // dtItemValue: '0002'
        },
        filterData: {
          staffName: {
            key: 'staffName',
            type: 'input',
            placeholder: '姓名'
          },
          deptId: {
            clearable: false,
            key: 'deptId',
            type: 'selectTree',
            title: '部门',
            placeholder: '请选择部门',
            options: [],
            props: {
              label: 'label',
              value: 'id',
              parent: 'parentId',
              children: 'children'
            },
            changeFn: _ => {
              this.$refs.followCadre.$refs.customSelect.focus()
            }
          }
        },
        columns: [
          { property: 'staffName', label: '跟班干部' },
          { property: 'deptName', label: '所属部门' },
          { property: 'phone', label: '联系方式' }
        ],
        total: 0,
        filterFn: getStaffList
      },
      selectTableModelWorkLeader: { // 作业领导
        filterForm: {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
          // 暂时注释
          // dtId: 'POSITION_TYPE',
          // dtItemValue: '0001'
        },
        filterData: {
          staffName: {
            key: 'staffName',
            type: 'input',
            placeholder: '姓名'
          },
          deptId: {
            clearable: false,
            key: 'deptId',
            type: 'selectTree',
            title: '部门',
            placeholder: '请选择部门',
            options: [],
            props: {
              label: 'label',
              value: 'id',
              parent: 'parentId',
              children: 'children'
            },
            changeFn: _ => {
              this.$refs.workLeader.$refs.customSelect.focus()
            }
          }
        },
        columns: [
          { property: 'staffName', label: '作业领导' },
          { property: 'deptName', label: '所属部门' },
          { property: 'phone', label: '联系方式' }
        ],
        total: 0,
        filterFn: getStaffList
      },
      selectTableModelInspectPeople: { // 巡视人员
        filterForm: {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
        },
        filterData: {
          staffName: {
            key: 'staffName',
            type: 'input',
            placeholder: '姓名'
          }
          // deptId: {
          //   key: 'deptId',
          //   type: 'selectTree',
          //   title: '部门',
          //   placeholder: '请选择部门',
          //   options: [],
          //   props: {
          //     label: 'label',
          //     value: 'id',
          //     parent: 'parentId',
          //     children: 'children'
          //   },
          //   changeFn: _ => {
          //     this.$refs.inspectPeopleList.$refs.customSelect.change()
          //   }
          // }
        },
        columns: [
          { prop: 'staffName', label: '巡视人员' },
          { prop: 'deptName', label: '所属部门' }
        ],
        total: 0,
        filterFn: getStaffList
      },
      dataList: {
        deptData: [], // 部门树
        lineData: [], // 线路
        inspectPeopleList: [], // 巡视人员
        followLeaderData: [], // 跟班领导
        followCadreData: [], // 跟班干部
        workLeaderData: [], // 作业领导人
        inspectTypeData: [], // 巡视类型
        inspectWayData: [] // 巡视方式
      },
      rules: {
        inspectDate: [
          { required: true, message: '请填选巡视日期', trigger: 'blur' }
        ],
        lineId: [
          { required: true, message: '请选择线路名称', trigger: 'change' }
        ],
        deptId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        workDateTimeRange: [
          { required: true, message: '请填选作业时间', trigger: 'blur' }
        ],
        dictInspectTypeId: [
          { required: true, message: '请选择巡视类型', trigger: 'change' }
        ],
        // followLeader: [
        //   { required: true, message: '请选择跟班领导', trigger: 'change' }
        // ],
        // followCadre: [
        //   { required: true, message: '请选择跟班干部', trigger: 'change' }
        // ],
        workLeader: [
          { required: true, message: '请选择作业领导人', trigger: 'change' }
        ],
        inspectPeopleList: [
          { required: true, message: '请选择巡视人员', trigger: 'change' }
        ],
        inspectRange: [
          { required: true, message: '请填写巡视区段', trigger: 'blur' }
        ],
        inspectContent: [
          { required: true, message: '请填写巡视内容', trigger: 'blur' }
        ],
        dictInspectWayId: [
          { required: true, message: '请选择巡视方式', trigger: 'change' }
        ],
        inspectPersonCount: [
          { required: true, message: '请填写总人数', trigger: 'blur' },
          { validator: valiInt, trigger: 'blur' }
        ],
        isNormal: [
          { required: true, message: '请选择是否异常', trigger: 'change' }
        ],
        problemContent: [
          { required: true, message: '请填写存在问题', trigger: 'blur' }
        ],
        treatment: [
          { required: true, message: '请填写处理情况', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'dialog.visible'() {
      if (this.dialog.visible) {
        if (this.dialog.type !== 'add') {
          this.dialog.form = this.handleDataForm(this.dialog.form)
        }
        // 附件
        var tempArr = []
        this.dialog.form.filesList.forEach(item => {
          tempArr.push(item.filePath)
        })
        this.showFile(tempArr, 1, 0, 0, false, this.dialog.form.filesList)

        // 重置页码、查询
        this.getList()
        this.getStaffList()
      }
    }
  },
  methods: {
    // 处理表单数据
    handleDataForm(data) {
      data.inspectPeople = data.inspectPeople ? data.inspectPeople.split(',') : []
      data.inspectPeopleId = data.inspectPeopleId ? data.inspectPeopleId.split(',') : []
      data.inspectPeopleList = []
      if (data.inspectPeople.length) {
        for (var i in data.inspectPeople) {
          var obj = {
            staffName: data.inspectPeople[i],
            staffId: data.inspectPeopleId[i]
          }
          data.inspectPeopleList.push(obj)
        }
      }
      // 作业时间
      var workBeginDate = data.workBeginDate ? data.workBeginDate : ''
      var workEndDate = data.workEndDate ? data.workEndDate : ''
      if (workBeginDate && workEndDate) {
        data.workDateTimeRange = [workBeginDate, workEndDate]
      }
      return data
    },

    // 显示附件
    showFile(pathList, type, key, index, isDetail, fileList) {
      this.fileModal = {
        title: '',
        visible: true,
        pathList: pathList,
        fileList: fileList,
        type,
        bizType: '1',
        key,
        index,
        isDetail: isDetail,
        uploadType: 'file'
      }
    },
    uploadSuccess(filelist, type, key, index, fileArr) { // 上传成功
      this.dialog.form.filesList = fileArr
      this.notifiySuccess('上传成功')
    },

    // 获取下拉数据、字典
    getList() {
      // 获取线路
      getLineList({ railType: '' }).then(response => {
        this.dataList.lineData = response.data
      })

      // 获取本部门及下属树
      getDeptAndSubDeptList({ deptCode: this.dialog.deptCode }).then(response => {
        this.dataList.deptData = response.data
      })

      // 获取角色管理部门树
      findManageDeptTree().then(response => {
        this.selectTableModelFollowLeader.filterData.deptId.options = response.data
        this.selectTableModelFollowCadre.filterData.deptId.options = response.data
        this.selectTableModelWorkLeader.filterData.deptId.options = response.data
        // this.selectTableModelInspectPeople.filterData.deptId.options = response.data
      })

      // 巡视类型
      getListFindByDtId({ dtId: 'DAILY_MUL_INSPECT_TYPE' }).then(response => {
        this.dataList.inspectTypeData = response.data
      })

      // 巡视方式
      getListFindByDtId({ dtId: 'DAILY_MUL_INSPECT_WAY' }).then(response => {
        this.dataList.inspectWayData = response.data
      })
    },

    // 选择跟班干部
    changeTableItemFollowCadre(row) {
      var tempData = this.dialog.form
      tempData.followCadre = row.staffName
      tempData.followCadrePhone = row.phone
      tempData.followCadreId = row.deptId
      this.dialog.form = JSON.parse(JSON.stringify(tempData))
    },

    // 选择跟班领导
    changeTableItemFollowLeader(row) {
      var tempData = this.dialog.form
      tempData.followLeader = row.staffName
      tempData.followLeaderPhone = row.phone
      tempData.followLeaderId = row.deptId
      this.dialog.form = JSON.parse(JSON.stringify(tempData))
    },

    // 作业领导人
    changeTableItemWorkLeader(row) {
      var tempData = this.dialog.form
      tempData.workLeader = row.staffName
      tempData.workLeaderId = row.deptId
      this.dialog.form = JSON.parse(JSON.stringify(tempData))
    },

    // 选择巡视人员
    changeTableItemInspectPeople(data) {
      this.dialog.form.inspectPeopleList = data.map(item => ({
        staffId: item.staffId,
        staffName: item.staffName,
        deptId: item.deptId,
        deptName: item.deptName
      }))
    },

    // 计算时间差
    getMinutes(dateTimeRange, minuteString) {
      if (dateTimeRange) {
        var startTime = new Date(dateTimeRange[0])
        var endTime = new Date(dateTimeRange[1])
        if (startTime || endTime) {
          var totalMinutes = 0
          totalMinutes = Math.floor((endTime - startTime) / (1000 * 60))
        }
        if (minuteString === 'workSpendMinutes') {
          this.dialog.form.workSpendMinutes = totalMinutes || 0
        }
      } else {
        if (minuteString === 'workSpendMinutes') {
          this.dialog.form.workSpendMinutes = 0
        }
      }
    },

    // 获取人员信息接口
    getStaffList() {
      this.$nextTick(_ => {
        // 跟班领导
        this.dataList.followLeaderData = []
        this.selectTableModelFollowLeader.total = 0
        this.selectTableModelFollowLeader.filterForm = Object.assign({}, this.selectTableModelFollowLeader.filterForm, {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
        })
        // 跟班干部
        this.dataList.followCadreData = []
        this.selectTableModelFollowCadre.total = 0
        this.selectTableModelFollowCadre.filterForm = Object.assign({}, this.selectTableModelFollowCadre.filterForm, {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
        })
        // 作业领导人
        this.dataList.workLeaderData = []
        this.selectTableModelWorkLeader.total = 0
        this.selectTableModelWorkLeader.filterForm = Object.assign({}, this.selectTableModelWorkLeader.filterForm, {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
        })
        // 巡视人员
        this.dataList.inspectPeopleData = []
        this.selectTableModelInspectPeople.total = 0
        this.selectTableModelInspectPeople.filterForm = Object.assign({}, this.selectTableModelInspectPeople.filterForm, {
          page: 1,
          size: 10,
          staffName: '',
          deptId: ''
        })
        const form = this.selectTableModelFollowLeader.filterForm
        getStaffList(form)
          .then((response) => {
            // 跟班领导
            this.dataList.followLeaderData = response.data.records
            this.selectTableModelFollowLeader.total = response.data.total
            // 跟班干部
            this.dataList.followCadreData = response.data.records
            this.selectTableModelFollowCadre.total = response.data.total
            // 作业领导人
            this.dataList.workLeaderData = response.data.records
            this.selectTableModelWorkLeader.total = response.data.total
            // 巡视人员
            this.dataList.inspectPeopleData = response.data.records
            this.selectTableModelInspectPeople.total = response.data.total
          })
      })
    },

    // 回调方法
    updateData() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.dialog.loading = true
          // 巡视人员
          if (this.dialog.form.inspectPeopleList.length) {
            var inspectPeople = []
            var inspectPeopleId = []
            for (var j in this.dialog.form.inspectPeopleList) {
              inspectPeople.push(this.dialog.form.inspectPeopleList[j].staffName)
              inspectPeopleId.push(this.dialog.form.inspectPeopleList[j].staffId)
            }
            this.dialog.form.inspectPeople = inspectPeople.join(',')
            this.dialog.form.inspectPeopleId = inspectPeopleId.join(',')
          }
          // 检修时间
          if (this.dialog.form.workDateTimeRange) {
            this.dialog.form.workBeginDate = this.dialog.form.workDateTimeRange[0]
            this.dialog.form.workEndDate = this.dialog.form.workDateTimeRange[1]
          } else {
            this.dialog.form.workBeginDate = ''
            this.dialog.form.workEndDate = ''
          }
          addEditMulInspectData(this.dialog.form)
            .then((response) => {
              this.dialog.loading = false
              this.$emit('updateData', this.dialog.form)
            })
            .catch((_) => {
              this.dialog.loading = false
            })
        }
      })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    changeLine() {}
  }
}
</script>
<style lang="scss">
.jcw-repair-edit {
  .time-box {
    display: flex;
    .minutes-item {
      display: inline-block;
      padding-top: 8px;
      height: 0px;
      white-space: nowrap;
    }
  }
}
</style>
